package com.backend.plat.sa.controller;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.backend.dto.RolesDto;
import com.backend.dto.UserDto;
import com.backend.dto.UserDtoForBackend;
import com.backend.dto.UserRelateOrgDto;
import com.google.gson.reflect.TypeToken;
import com.oxygen.constants.Constant;
import com.oxygen.dto.ApiFinalResponse;
import com.oxygen.enums.BackendApiMethodEnum;
import com.oxygen.util.JsonUtil;
import com.oxygen.util.Md5Util;
import com.oxygen.web.WebHelper;

/**
 * 前台用户管理
 * @author jason
 */
@Controller
@RequestMapping(value = "/user")
public class BackendUserAction extends BaseAction {
	
	private static final String page_edit = "/user/edit";
	
	/**
	 * 进入新增页面
	 * @param req
	 * @param rsp
	 */
	@RequestMapping(value = "/add")
	public String add(HttpServletRequest req, HttpServletResponse rsp) {
		try {
			//得到角色列表
			Map<String, Object> appendMap1 = new HashMap<String, Object>();
			appendMap1.put(Constant.PAGE, req.getParameter(Constant.PAGE));
			appendMap1.put(Constant.PAGE_SIZE, req.getParameter(Constant.PAGE_SIZE));
			String json1 = this.callApi(BackendApiMethodEnum.USER_GETROLES, appendMap1, req);
			Type type1 = new TypeToken<Map<String, ApiFinalResponse<List<RolesDto>>>>() {
			}.getType();
			Map<String, ApiFinalResponse<List<RolesDto>>> retMap1 = JsonUtil.jsonToObject(json1, type1);
			if (retMap1 != null) {
				List<RolesDto> rolesList = retMap1.get(BackendApiMethodEnum.USER_GETROLES.getCode()).getResults();
				req.setAttribute("rolesList", rolesList);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return page_edit;
	}
	
	@RequestMapping(value = "/search")
	public String search(HttpServletRequest req, HttpServletResponse rsp) {
		String menuId = req.getParameter("menuId");
		req.setAttribute("menuId", menuId);
		WebHelper.setRequestAttributesFromRequestParam(req);
		return "/user/search";
	}
	@RequestMapping(value = "/list")
	public String list(HttpServletRequest req, HttpServletResponse rsp) {
		String menuId = req.getParameter("menuId");
		req.setAttribute("menuId", menuId);
		Map<String, Object> appendMap = new HashMap<String, Object>();
		appendMap.put(Constant.PAGE, req.getParameter(Constant.PAGE));
		appendMap.put(Constant.PAGE_SIZE, req.getParameter(Constant.PAGE_SIZE));
		String json = this.callApi(BackendApiMethodEnum.USER_QUERYUSERLIST, appendMap, req);
		Type type = new TypeToken<Map<String, ApiFinalResponse<List<UserDtoForBackend>>>>() {
		}.getType();
		Map<String, ApiFinalResponse<List<UserDtoForBackend>>> retMap = JsonUtil.jsonToObject(json, type);
		
		if (retMap != null) {
			retMap.get(BackendApiMethodEnum.USER_QUERYUSERLIST.getCode()).getResults();
			req.setAttribute("apiRsp", retMap.get(BackendApiMethodEnum.USER_QUERYUSERLIST.getCode()));
		}
		req.setAttribute("page_size", appendMap.get(Constant.PAGE_SIZE));
		WebHelper.setRequestAttributesFromRequestParam(req);
		return "/user/list";
	}

	@RequestMapping(value = "/edit/{id}")
	public String edit(@PathVariable String id, HttpServletRequest req, HttpServletResponse rsp) {
		//得到用户信息
		Map<String, Object> appendMap = new HashMap<String, Object>();
		appendMap.put("id", id);
		String json = this.callApi(BackendApiMethodEnum.USER_QUERYUSERBYID, appendMap, req);
		Type type = new TypeToken<Map<String, ApiFinalResponse<UserDto>>>() {
		}.getType();
		Map<String, ApiFinalResponse<UserDto>> retMap = JsonUtil.jsonToObject(json, type);
		UserDto UserDto = retMap.get(
				BackendApiMethodEnum.USER_QUERYUSERBYID.getCode()).getResults();
		
		
		List<UserRelateOrgDto> orgList = UserDto.getOrgList();
		
	    List<String> orgIdList = new ArrayList<String>();
		
		for (UserRelateOrgDto userRelateOrgDto : orgList) {
			orgIdList.add(userRelateOrgDto.getOrgId().toString());
		}
		UserDto.setCheckedOrgId(StringUtils.join((String[])orgIdList.toArray(new String[orgIdList.size()]),","));
		if (retMap != null && retMap.get(BackendApiMethodEnum.USER_QUERYUSERBYID.getCode()) != null) {
			req.setAttribute("user", UserDto);
		}
		//得到角色列表
		Map<String, Object> appendMap1 = new HashMap<String, Object>();
		appendMap1.put(Constant.PAGE, req.getParameter(Constant.PAGE));
		appendMap1.put(Constant.PAGE_SIZE, req.getParameter(Constant.PAGE_SIZE));
		String json1 = this.callApi(BackendApiMethodEnum.USER_GETROLES, appendMap1, req);
		Type type1 = new TypeToken<Map<String, ApiFinalResponse<List<RolesDto>>>>() {
		}.getType();
		Map<String, ApiFinalResponse<List<RolesDto>>> retMap1 = JsonUtil.jsonToObject(json1, type1);
		if (retMap1 != null) {
			List<RolesDto> rolesList = retMap1.get(BackendApiMethodEnum.USER_GETROLES.getCode()).getResults();
			req.setAttribute("rolesList", rolesList);
		}
		return "/user/edit";
	}
	
	/**
	 * 更新用户信息
	 * @param req
	 * @param rsp
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public void update(HttpServletRequest req, HttpServletResponse rsp) {
		try {
			Map<String, Object> appendMap = new HashMap<String, Object>();
			appendMap.put("id", req.getParameter("id"));
			appendMap.put("email", req.getParameter("email"));
			appendMap.put("nickName", req.getParameter("nickName"));
			appendMap.put("realName", req.getParameter("realName"));	
			String roleIds = StringUtils.join(req.getParameterValues("roleIds"), ",");
			String orgIds = req.getParameter("ids");
			appendMap.put("roleIds", roleIds);
			appendMap.put("orgIds", orgIds);
			WebHelper.outputJson(this.callApi(
					BackendApiMethodEnum.USER_UPDATEUSERS, appendMap, req),
					rsp);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 保存用户信息
	 * @param req
	 * @param rsp
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public void save(HttpServletRequest req, HttpServletResponse rsp) {
		try {
			Map<String, Object> appendMap = new HashMap<String, Object>();
			String roleIds = StringUtils.join(req.getParameterValues("roleIds"), ",");
			String orgIds = req.getParameter("ids");
			appendMap.put("roleIds", roleIds);
			appendMap.put("orgIds", orgIds);
			appendMap.put("userType","backend");
			appendMap.put("userTypeName", "后台超管");
			appendMap.put("isSuperuser", "1");
			appendMap.put("password", Md5Util.encodeString("123456"));
			appendMap.put("registSource", "backendSystem");
			WebHelper.outputJson(this.callApi(
					BackendApiMethodEnum.USER_REGISTER, appendMap, req),
					rsp);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
